package com.weiyuwqj.api.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
import com.weiyuwqj.api.exception.ExceptionMessage;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

public class ExceptionInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // TODO Auto-generated method stub  
        return true;
    }


    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        HashMap<String, String> msg = new HashMap<String, String>();
        if (ex != null) {
            if (ex instanceof CrowdException) {
                msg.put("result", "fail");
                String code = ((CrowdException) ex).getCode();
                String message = ExceptionMessage.exceptionMessage.get(code);
                msg.put("messageCode", code);
                msg.put("messageText", message);
                msg.put("recode", "01");
            } else if (ex instanceof HfException) {
                msg.put("result", "fail");
                String code = ((HfException) ex).getCode();
                String message = ((HfException) ex).getMessageText();
                msg.put("messageCode", code);
                msg.put("messageText", message);
                msg.put("recode", "01");
            } else {
                msg.put("result", "fail");
                msg.put("messageCode", "sys.error");
                msg.put("recode", "01");
            }
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(msg);
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            PrintWriter out = response.getWriter();
            out.print(json);
            out.flush();
            out.close();
        }
    }

}  